<?php

namespace App\Http\Controllers\Api;

use App\Model\Butler;
use App\Model\Picture;
use App\Model\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class NeighbourController extends BaseController {
    //邻里圈
    private $user;
    public function __construct(){
        $this->user=$this->GetUser();
    }

    //发表动态
    public function send(Request $request){
        $data['user_id']=$this->user['user_id'];
        $data['content']=$request->input('content');
        $data['image']=$request->input('image');
        $data['create_time']=time();
        $res=DB::table('neighbour')->insert($data);
        if ($res) {
            $info=['code'=>1,'msg'=>'发表成功'];
        }else{
            $info=['code'=>0,'msg'=>'发表失败'];
        }
        return json_encode($info);
    }

    //获取邻邻里圈动态
    public function get(){
        //小区公告
        $info=DB::table('info')->orderByDesc('create_time')->limit(2)->get();
        foreach ($info as $k=>$v){
            $info[$k]->content=mb_substr(strip_tags($v->content),0,100,'utf-8');
        }

        //精选
        $jinxuan=DB::table('info')->orderByDesc('create_time')->limit(2)->get();
        foreach ($info as $k=>$v){
            $info[$k]->content=mb_substr(strip_tags($v->content),0,100,'utf-8');
        }

        //动态
        $list=DB::table('neighbour')->where('status',1)->orderBy('create_time','desc')
            ->get()->each(function($item,$key){
                $item->create_time=date('Y-m-d H:i:s',$item->create_time);
                if(!is_null($item->image)){
                    $item->image=$this->GetImage($item->image);
                }
                $item->avatarUrl=$this->GetUserInfo($item->user_id)['avatarUrl'];
                $item->nickName=$this->GetUserInfo($item->user_id)['nickName'];
                $item->zancount=$this->zancount($item->id);
                $item->comment=$this->GetComment($item->id);
                $item->iszan=$this->iszan($item->id,$this->user['user_id']);
                return $item;
            });

        return json_encode(['info'=>$info,'jinxuan'=>$jinxuan,'list'=>$list]);
    }

    //判断是不是点过赞
    public function iszan($id,$user_id){
        $where['user_id']=$user_id;
        $where['neighbour_id']=$id;
        $res=DB::table('neighbour_zan')->where($where)->first();
        if ($res){
            return 1;
        }else{
            return 0;
        }
    }

    //获取评论
    public function GetComment($id){
        $list=DB::table('neighbour_comment')->where('neighbour_id',$id)
            ->get()->each(function ($item,$key){
                $item->nickName=$this->GetUserInfo($item->user_id)['nickName'];
                return $item;
            });
        return $list;
    }


    //赞数
    public function zancount($id){
        return DB::table('neighbour_zan')->where('neighbour_id',$id)->count();
    }

    //用户信息
    public function GetUserInfo($user_id){
        $list=User::where('user_id',$user_id)->first();
        return $list;
    }

    //数组转图片
    public function GetImage($image){
        $arr=explode(',',$image);
        $data=[];
        foreach ($arr as $k=>$v){
            array_push($data,$this->getimg($v));
        }
        return $data;
    }

    //获取图片url
    public function getimg($id){
        $list=DB::table('file')->where('file_id',$id)->first();
        return $list->url;
    }


    //我的房屋
    public function myhouse(Request $request){
        $data=$request->all();
        $data['user_id']=$this->user['user_id'];
        $list=DB::table('user_house')->where('user_id',$data['user_id'])->get()->each(function ($item,$key){
        	$item['house']=$this->GetHouse($item->house_id);
        });
        return json_encode($list);
    }

    
    public function GetHouse($house_id){
    	$where['id']=$house_id;
    	$list=DB::table('user_house')->where($where)->first();
    	return $list;
    	
    }


     //我的房卡
      public function mycart(Request $request){
      	$where['user_id']=$this->user['user_id'];
      	$list=DB::table('user_card')->where($where)->all();
      	return json_encode($list);
      	
      }
    

    //添加我的房屋
    public function addhouse(Request $request){
        $data=$request->all();
        
        $where['region']=$data['region'];
        $where['house']=$data['house'];
        $where['owner']=10;
        if($data['owner']==20){
         $check=DB::table('user_house')->where($where)->first();
        if ($check) {
        $info['who']=$this->user['user_id'];
        $info['user_id']=$check->user_id;
        $info['region']=$check->region;
        $info['house']=$check->house;
        $info['status']=10;
        $info['create_time']=time();
        DB::table('house_info')->insert($info);
           }
        }
        
        $data['user_id']=$this->user['user_id'];
        $data['create_time']=time();
        unset($data['token']);
        $res=DB::table('user_house')->insert($data);
        if ($res) {
            $info=['code'=>1,'msg'=>'添加成功'];
        }else{
            $info=['code'=>0,'msg'=>'添加失败'];
        }
        return json_encode($info);
    }




    //添加我的房屋
    public function addcart(Request $request){
        $data=$request->all();
        $where['id']=$data['house_id'];
        $check=DB::table('user_house')->where($where)->first();
        
        if($check->owner==10){
        $info['who']=$this->user['user_id'];
        $info['user_id']=$check->user_id;
        $info['region']=$check->region;
        $info['house']=$check->house;
        $info['status']=10;
        $info['type']=20;
        $info['create_time']=time();
        DB::table('house_info')->insert($info);
           }
       
        $data['user_id']=$this->user['user_id'];
        $data['create_time']=time();
        unset($data['token']);
        $res=DB::table('user_card')->insert($data);
         
        if ($res) {
            $info=['code'=>1,'msg'=>'申请成功'];
        }else{
            $info=['code'=>0,'msg'=>'申请失败'];
        }
        return json_encode($info);
    }




        //我的消息
       public function info(Request $request){
       $data=$request->all();
       $where['user_id']=$this->user['user_id'];
       $list=DB::table('house_info')->get(['who','create_time','region','house','status'])->each(function ($item,$key){
       	$item->create_time=date('Y-m-d',$item->create_time);
       	$item->who=$this->UserInfo($item->who)->nickName;
       	return $item;
       });
       
       return json_encode($list);
       }

  

    //获取我的朋友圈
    public function getmyneighbour(Request $request){

        //动态
        $data=$request->all();
        $where['user_id']=$this->user['user_id'];
        $list=DB::table('neighbour')->where($where)->orderBy('create_time','desc')->get();

         /* 年份 */
        $data=[];
          foreach ($list as $k=>$v){
              array_push($data,date('Y',$v->create_time));
          }
        $data=array_unique($data);
        rsort($data);
        /* 年份 */


        $data2=[];
        $data2[0]=time();
        foreach ($data as $k=>$v){
          array_push($data2,strtotime($v.'-01-01'));
        }

        $data3=[];
        for ($i=0;$i<count($data2)-1;$i++){
            array_push($data3,$this->friends($this->user['user_id'],$data2[$i],$data2[$i+1]));
        }

      return json_encode(['date'=>$data,'list'=>$data3]);

    }

    //获取朋友圈
    public function friends($user_id,$start,$end){
        $list=DB::table('neighbour')->where('user_id',$user_id)
            ->whereBetween('create_time',[$end,$start])->orderBy('create_time','desc')
            ->get()->each(function($item,$key){
                $item->create_time=date('Y-m-d',$item->create_time);
                if (!is_null($item->image)){
                    $item->image=$this->GetImage($item->image);
                }
                return $item;
            });
        return $list;
    }


    //删除朋友圈
    public function delneighbour(Request $request){
        $id=$request->input('id');
        DB::beginTransaction();
        try{
            //中间逻辑代码
            DB::table('neighbour')->delete($id);
            DB::table('neighbour_zan')->where('neighbour_id',$id)->delete($id);
            DB::table('neighbour_comment')->where('neighbour_id',$id)->delete($id);
            DB::commit();
            return json_encode(['code'=>1,'msg'=>'删除成功']);
        }catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            return json_encode(['code'=>0,'msg'=>'删除失败']);
        }

    }

     //删除评论
     public function delcomment(Request $request){
     	   $id=$request->input('id');
           $res=DB::table('neighbour_comment')->where('id',$id)->delete($id);
           if($res){
           	 return json_encode(['code'=>1,'msg'=>'删除成功']);
           }else{
           	 return json_encode(['code'=>0,'msg'=>'删除失败']);
           }

     }

     //删除点赞
     public function delzan(Request $request){
     	    $data=$request->all();
            $where['user_id']=$this->user['user_id'];
            $where['neighbour_id']=$request->input('neighbour_id');
     	    $res=DB::table('neighbour_zan')->where($where)->delete();
           if($res){
           	 return json_encode(['code'=>1,'msg'=>'删除成功']);
           }else{
           	  return json_encode(['code'=>0,'msg'=>'删除失败']);
           }
     }

     //删除我的房屋
     public function delhouse(Request $request){
         $where['id']=$request->input('id');
         $res=DB::table('user_house')->where($where)->delete();
         if($res){
             return json_encode(['code'=>1,'msg'=>'删除成功']);
         }else{
             return json_encode(['code'=>0,'msg'=>'删除失败']);
         }
     }

     //更新我的房屋
    public function updatehouse(Request $request){
        $id=$request->input('id');
        $data=$request->all();
        unset($data['token']);
        $res=DB::table('user_house')->where('id',$id)->update($data);
        if($res){
            return json_encode(['code'=>1,'msg'=>'更新成功']);
        }else{
            return json_encode(['code'=>0,'msg'=>'更新失败']);
        }
    }

    //点赞
    public function zan(Request $request){
        $data=$request->all();
        $data['user_id']=$this->user['user_id'];
        unset($data['token']);
        $check=DB::table('neighbour_zan')->where($data)->first();
        if ($check){
            return json_encode(['code'=>0,'msg'=>'请勿重复点赞']);
        }
        $data['create_time']=time();
        $res=DB::table('neighbour_zan')->insert($data);
        if ($res) {
            $info=['code'=>1,'msg'=>'点赞成功'];
        }else{
            $info=['code'=>0,'msg'=>'点赞失败'];
        }
        return json_encode($info);
    }

    //评价
    public function comment(Request $request){
        $data=$request->all();
        $data['user_id']=$this->user['user_id'];
        $data['create_time']=time();
        unset($data['token']);
        $res=DB::table('neighbour_comment')->insert($data);
        if ($res) {
            $info=['code'=>1,'msg'=>'评价成功'];
        }else{
            $info=['code'=>0,'msg'=>'评价失败'];
        }
        return json_encode($info);
    }

    //快递查询
     public function express(Request $request){
         date_default_timezone_set('PRC');
         //背景墙图片
         $img=Picture::where('id',2)->first();
         $img=$this->GetImg($img->image_id);

        $where['user_id']=$this->user['user_id'];
        $where['delivery_status']=20;
        $list=DB::table('order')->where($where)->get(['order_id','express_no','express_company','express_code'])
           ->each(function ($item,$key){
            $item->time=date('m-d',strtotime($this->checkexpress($item)['data'][0]['time']));
            $item->status=$this->checkexpress($item)['data'][0]['status'];
        });
        $url[0]='http://mhjy.gzfloat.com/api/iframe';
        $url[1]='http://mhjy.gzfloat.com/api/iframe';
        
        return json_encode(['img'=>$img,'list'=>$list,'url'=>$url]);
     }



    //查快递
     public function checkexpress($data){
         //参数设置
         $key = 'RQBSzsuB4408';						//客户授权key
         $customer = '6B77D43C6B6CD8663296E79C515B8730';					//查询公司编号
         $param = array (
             'com' =>$data->express_code,			//快递公司编码
             'num' =>$data->express_no,	//快递单号
             'phone' => '',				//手机号
             'from' => '',				//出发地城市
             'to' => '',					//目的地城市
             'resultv2' => '1'			//开启行政区域解析
         );

         //请求参数
         $post_data = array();
         $post_data["customer"] = $customer;
         $post_data["param"] = json_encode($param);
         $sign = md5($post_data["param"].$key.$post_data["customer"]);
         $post_data["sign"] = strtoupper($sign);

         $url = 'http://poll.kuaidi100.com/poll/query.do';	//实时查询请求地址

         $params = "";
         foreach ($post_data as $k=>$v) {
             $params .= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
         }
         $post_data = substr($params, 0, -1);
         //发送post请求
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         $result = curl_exec($ch);
         $data = str_replace("\"", '"', $result );
         $data = json_decode($data,true);
         return $data;
     }


      //查快递
      public function findexpress(Request $request){
          $express_code=$request->input('express_code');
          $express_no=$request->input('express_no');
          //参数设置
          $key = 'RQBSzsuB4408';						//客户授权key
          $customer = '6B77D43C6B6CD8663296E79C515B8730';					//查询公司编号
          $param = array (
              'com' =>$express_code,			//快递公司编码
              'num' =>$express_no,	//快递单号
              'phone' => '',				//手机号
              'from' => '',				//出发地城市
              'to' => '',					//目的地城市
              'resultv2' => '1'			//开启行政区域解析
          );

          //请求参数
          $post_data = array();
          $post_data["customer"] = $customer;
          $post_data["param"] = json_encode($param);
          $sign = md5($post_data["param"].$key.$post_data["customer"]);
          $post_data["sign"] = strtoupper($sign);

          $url = 'http://poll.kuaidi100.com/poll/query.do';	//实时查询请求地址

          $params = "";
          foreach ($post_data as $k=>$v) {
              $params .= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
          }
          $post_data = substr($params, 0, -1);
          //发送post请求
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_HEADER, 0);
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          $result = curl_exec($ch);
          $data = str_replace("\"", '"', $result );
          $data = json_decode($data,true);
          return $data;
      }

      //确认收货
      public function comfirm(Request $request){
       $where['order_id']=$request->input('order_id');
       $data['receipt_status']=20;
       $res=DB::table('order')->where($where)->update($data);
       if ($res){
          return json_encode(['code'=>1,'msg'=>'收货成功']);
       }else{
         return json_encode(['code'=>0,'msg'=>'收货失败']);
        }
      }


}
